<script setup lang="ts">
import { onShow } from "@dcloudio/uni-app";

type TabBarIcon = {
  name: string;
  prefix?: string;
};

type TabBarItem = {
  name: string;
  label?: string;
  icon: TabBarIcon;
  activeIcon?: TabBarIcon;
};

const list: Array<TabBarItem> = [
  {
    name: "home",
    label: "首页",
    icon: {
      name: "home",
      prefix: "m-icon",
    },
    activeIcon: {
      name: "home-filled",
      prefix: "m-icon",
    },
  },
  {
    name: "chat",
    label: "chat",
    icon: {
      name: "add",
      prefix: "m-icon",
    },
  },
  {
    name: "my",
    label: "我的",
    icon: {
      name: "user",
      prefix: "m-icon",
    },
    activeIcon: {
      name: "user-filled",
      prefix: "m-icon",
    },
  },
];

const current = ref("home");

function onTap(name: string) {
  current.value = name;
  const routeMap: Record<string, string> = {
    home: "/pages/index/index",
    chat: "/pages/chat/index",
    my: "/pages/my/index",
  };

  const url = routeMap[name];
  if (url) {
    uni.switchTab({
      url,
      success: () => {
        current.value = name;
      },
    });
  }
}

// 监听页面显示，同步当前页面对应的tab状态
onShow(() => {
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const route = currentPage?.route || "";

  // 根据当前路由设置选中状态
  if (route.includes("index/index")) {
    current.value = "home";
  } else if (route.includes("chat/index")) {
    current.value = "chat";
  } else if (route.includes("my/index")) {
    current.value = "my";
  }
});

// // 监听当前页面路径，同步更新选中状态
// onShow(() => {
//   const pages = getCurrentPages();
//   const currentPage = pages[pages.length - 1];
//   const route = currentPage?.route || "";

//   let selectedIndex = 0;
//   if (route.includes("index/index")) {
//     current.value = "home";
//     selectedIndex = 0;
//   } else if (route.includes("chat/index")) {
//     current.value = "chat";
//     selectedIndex = 1;
//   } else if (route.includes("my/index")) {
//     current.value = "my";
//     selectedIndex = 2;
//   }

//   // 更新tabBar选中状态

// });
</script>

<template>
  <view
    class="tab-bar fixed inset-x-0 bottom-0 flex bg-whit border-t border-gray-200"
  >
    <view
      v-for="item in list"
      :key="item.name"
      class="flex-1 flex-center py-2 px-4"
      :class="{
        'is-active': item.name === current,
      }"
      @tap="onTap(item.name)"
    >
      <view style="width: 100rpx">
        <t-icon v-bind="item.icon" class="icon" />
        <view class="text-xs text-center">
          {{ item.label }}
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
.tab-bar {
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
.is-active {
  color: var(--primary-color);
  .icon {
    animation: ff 1s forwards;
  }
}
@keyframes ff {
  0% {
    transform: translateY(0px);
  }
  50% {
    transform: translateY(-10px);
  }
  100% {
    transform: translateY(0px);
  }
}
</style>
